package com.situ.stmall.admin.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.stmall.admin.entity.APIResult;
import com.situ.stmall.admin.entity.Root;
import com.situ.stmall.admin.service.RootService;
import com.situ.stmall.admin.util.TokenUtil;
import com.situ.stmall.admin.util.TokenUtil.Token;

@Component //组件
public class RootInterceptor implements HandlerInterceptor{
	
	@Autowired
	private RootService rootService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("test");
		
		// 如果用户没有登陆，拦截
		//1.获取客户端传递来的token字符串
		String strToken = request.getHeader("token");
		System.out.println(strToken);
		if (strToken == null || strToken.length() == 0) {
			//用户未登录
			setResponse(response, "用户未登录，请登录后再进行操作");
			//拦截
			return false;
		}
		//2.解密token，时间有没有过期
		Token token = TokenUtil.parseToken(strToken);
		
		if (token.getStatus() == 1) {
			setResponse(response, "登录已过期，请重新登陆");
		}
		
		//3.是不是一个有效的用户
		
		String rootname = token.getCode();
		Root root = rootService.getByRootName(rootname);
		if (root == null) {
			setResponse(response, "当前用户不是一个有效用户，请重新登陆");
			return false;
		}
		
		//禁用
		if (root.getStatus() == 1) {
			setResponse(response, "用户已被禁用，请联系管理人员");
			return false;
		}
		
		//5.刷新token 重置有效时间
		strToken = TokenUtil.createToken(token.getCode());
		response.setHeader("token", strToken);
		
		return true;//放行
	}
	
	private void setResponse(HttpServletResponse response,String msg) throws IOException {
		APIResult apiResult = APIResult.unauthorized(msg);
		
		//将APIresult 转换成json字符串
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(apiResult);
		
		//由response返回
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(json);
	}
}
